'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 配置数据管理类
 * @author sundbcn@gmail.com (sun debing)
 */

var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var configUtil = require('../util/configUtil');

/**
 * Data model `new Data()`
 *
 * @param {Array}
 *
 */
var Data = function (name, path) {
    this.load(path);
};

/**
 * 加载数据
 * @param {[type]} name [description]
 * @param {[type]} path [description]
 */
Data.prototype.load = function (path) {
    this.data = JSON.parse(fs.readFileSync(path, 'utf8'));
};

/**
 * 长度
 * @return {[type]} [description]
 */
Data.prototype.length = function () {
    return _.size(this.data);
};

/**
 * 遍历
 * @param  {[type]} iterator [description]
 * @return {[type]}          [description]
 */
Data.prototype.any = function (iterator) {
    _.some(this.data, function (value, key) {
        return iterator(_.clone(value), key);
    });
};

/**
 *
 * @param  {[type]} iterator [description]
 * @return {[type]}          [description]
 */
Data.prototype.each = function (iterator) {
    _.each(this.data, function (value, key) {
        iterator(_.clone(value), key);
    });
};

/**
 *
 * @param  {[type]} iterator [description]
 * @return {[type]}          [description]
 */
Data.prototype.find = function (iterator) {
    return _.clone(_.find(this.data, iterator), true);
};

/**
 * find item by id
 *
 * @param id
 * @return {Obj}
 * @api public
 */
Data.prototype.findById = function (id) {
    return _.clone(this.data[id]);
};

/**
 * find all item
 *
 * @return {array}
 * @api public
 */
Data.prototype.all = function () {
    return this.data;
};

var DataApi = function () {
    this.load();
};

DataApi.prototype.load = function () {
    var self = this;
    var lang_config = configUtil.load('language');
    var config_path = path.join(__dirname, '../../config/data/' + lang_config.location + '/');
    fs.readdirSync(config_path).forEach(function (filename) {
        if (!/\.json$/.test(filename)) {
            return;
        }
        var name = path.basename(filename, '.json');
        var fullPath = config_path + filename;
        self[name] = new Data(name, fullPath);
    });
};

module.exports = new DataApi();
